import '../Scss/Theme.scss'
import { useState, useEffect } from 'react'
import { arrayMove, SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'
import { useEventEmitter } from 'ahooks'
import { DndContext } from '@dnd-kit/core'
import { ObjectToArray, TableRow } from '../../Configure/Common'
import { BackImageUrl, WebThemeBackImage } from '../../Router/MenuNav/DiyList/Theme/Common'
import { ThemeTypeDescriptive, ThemeTypeData } from '../../Router/MenuNav/DiyList/Theme/ThemeTypeList'
import { ThemeColorTitleList, ThemeColorBtn, optionsWithDisabled } from '../../Router/MenuNav/DiyList/Theme/Color'
import { operatingButtonList, HeaderOptionsData } from '../../Router/MenuNav/DiyList/Theme/HeaderOptions'
import { userInfoButtonList, HeaderUserInfoList, triggerList } from '../../Router/MenuNav/DiyList/Theme/HeaderUserInfo'
import { Button, Badge, Table, Switch, Select, Radio } from 'antd'

export const ThemeTypeSelect = ({ ModalEvent, data, Off }) => {
    const [Active, setActive] = useState(data.type)
    const ActiveRibbon = ({ text }) => {
        return (
            <div className="ActiveRibbon">
                <div>当前选中主题</div>
                <div>{text}</div>
            </div>
        )
    }
    const submit = () => {
        ModalEvent.emit({ layoutStyle: Active })
        Off()
    }
    return (
        <div className="ThemeTypeSelect">
            <div className="list">
                {Object.keys(ThemeTypeDescriptive).map(item => (
                    <div key={item} onClick={() => setActive(item)}>
                        {item === Active ? (
                            <Badge.Ribbon text={<ActiveRibbon text={ThemeTypeDescriptive[item].title} />}>
                                <ThemeTypeData theme={data.theme} type={item} img={data.img} />
                            </Badge.Ribbon>
                        ) : (
                            <ThemeTypeData theme={data.theme} type={item} img={data.img} />
                        )}
                    </div>
                ))}
            </div>
            <div className="Submit">
                <Button type="primary" onClick={submit}>
                    保存
                </Button>
            </div>
        </div>
    )
}

// 背景图片选择
export const ThemeBackImageSelect = ({ ModalEvent, data, Off }) => {
    const [Active, setActive] = useState(data.img)

    const submit = () => {
        ModalEvent.emit({ backImage: Active })
        Off()
    }

    return (
        <div className="ThemeBackImageSelect">
            <div className="list">
                <div onClick={() => setActive('')} style={{ '--theme': data.theme }}>
                    {Active === '' ? (
                        <Badge.Ribbon text="使用当前主题色">
                            <div />
                        </Badge.Ribbon>
                    ) : (
                        <div />
                    )}
                </div>
                {Object.keys(WebThemeBackImage).map(item => (
                    <div key={item} onClick={() => setActive(item)}>
                        {item === Active ? (
                            <Badge.Ribbon text="当前选中的背景图片">
                                <img src={`${BackImageUrl}${WebThemeBackImage[item]}`} alt="" />
                            </Badge.Ribbon>
                        ) : (
                            <img src={`${BackImageUrl}${WebThemeBackImage[item]}`} alt="" />
                        )}
                    </div>
                ))}
            </div>
            <div className="Submit">
                <Button type="primary" onClick={submit}>
                    保存
                </Button>
            </div>
        </div>
    )
}

// 主题颜色选择
export const ThemeColor = ({ ModalEvent, data, Off }) => {
    const [Active, setActive] = useState(data.theme)
    const ColorEvent = useEventEmitter()
    ColorEvent.useSubscription(val => setActive(val))

    const submit = () => {
        ModalEvent.emit(Active)
        Off()
    }

    return (
        <div className="ThemeColor">
            <div className="list">
                {ThemeColorTitleList.map(({ uuid, title, content, children }) => (
                    <div key={uuid}>
                        <div className="Title">
                            <div>{title}</div>
                            <div>{content}</div>
                        </div>
                        <div className="Box">
                            {ObjectToArray(children, 10).map((item, index) => (
                                <div key={index}>
                                    {Object.keys(item).map(key => (
                                        <ThemeColorBtn
                                            ColorEvent={ColorEvent}
                                            key={key}
                                            active={item[key] === Active}
                                            theme={item[key]}
                                            text={data.text}
                                            name={key}
                                        />
                                    ))}
                                </div>
                            ))}
                        </div>
                    </div>
                ))}
            </div>
            <div className="Submit">
                <Button type="primary" onClick={submit}>
                    保存
                </Button>
            </div>
        </div>
    )
}

// 头部操作栏
export const HeaderOptionsSet = ({ ModalEvent, data, Off }) => {
    const [dataSource, setDataSource] = useState([])
    const [ColorSelect, setColorSelect] = useState()
    const [TypeSelect, setTypeSelect] = useState()
    const [Options, setOptions] = useState([])
    const onDragEnd = ({ active, over }) => {
        if (active.id !== over?.id) {
            setDataSource(prev => {
                const activeIndex = prev.findIndex(i => i.uuid === active.id)
                const overIndex = prev.findIndex(i => i.uuid === over?.id)
                return arrayMove(prev, activeIndex, overIndex)
            })
        }
    }

    useEffect(() => {
        if (data) {
            const { type, color, list } = data.sort
            setTypeSelect(type)
            setColorSelect(color)
            setOptions(Object.keys(HeaderOptionsData).map(item => ({ label: item, value: item })))

            const oldObj = Object.values(operatingButtonList).filter(button => list.indexOf(button.uuid) === -1)
            const newObj = list.map(item => ({ ...operatingButtonList[item], isEnabled: true }))
            setDataSource([...newObj, ...Object.values(oldObj)])
        }
    }, [data])

    const SwitchChange = (uuid, e) => {
        dataSource.find(v => v.uuid === uuid).isEnabled = e
        setDataSource([...dataSource])
    }

    const OptionSubmit = () => {
        ModalEvent.emit({
            HeaderOptionsSet: {
                type: TypeSelect,
                color: ColorSelect,
                list: dataSource.filter(v => v.isEnabled).map(item => item.uuid),
            },
        })
        Off()
    }

    return (
        <div className="HeaderOptionsSet">
            <div className="label">
                <div>样式类型 : </div>
                <Select value={TypeSelect} bordered={false} options={Options} onChange={setTypeSelect} />
            </div>

            <div className="label">
                <div>图标颜色 : </div>
                <Radio.Group
                    options={optionsWithDisabled}
                    onChange={e => {
                        setColorSelect(e.target.value)
                    }}
                    value={ColorSelect}
                    optionType="button"
                    buttonStyle="solid"
                />
            </div>

            <DndContext onDragEnd={onDragEnd}>
                <SortableContext items={dataSource.map(i => i.uuid)} strategy={verticalListSortingStrategy}>
                    <Table
                        components={{ body: { row: TableRow } }}
                        rowKey="uuid"
                        pagination={false}
                        columns={[
                            { key: 'uuid', width: 50 },
                            { title: '图标', width: 80, dataIndex: 'icon' },
                            { title: '标题', width: 100, dataIndex: 'title' },
                            { title: '简介', dataIndex: 'content' },
                            {
                                title: '开关',
                                width: 80,
                                dataIndex: 'options',
                                render: (_, { uuid, isEnabled }) => [
                                    <Switch key={uuid} checked={isEnabled} onChange={e => SwitchChange(uuid, e)} />,
                                ],
                            },
                        ]}
                        dataSource={dataSource}
                        scroll={{ x: 1000, y: 500 }}
                    />
                </SortableContext>
            </DndContext>
            <div className="Submit">
                <Button type="primary" onClick={OptionSubmit}>
                    保存
                </Button>
            </div>
        </div>
    )
}

// 头部个人中心
export const HeaderUserInfoSet = ({ ModalEvent, data, Off }) => {
    const [TypeSelect, setTypeSelect] = useState()
    const [TriggerSelect, setTriggerSelect] = useState()
    const [dataSource, setDataSource] = useState([])
    const [Options, setOptions] = useState([])

    useEffect(() => {
        if (data) {
            const { type, trigger, list } = data.sort
            setTypeSelect(type)
            setTriggerSelect(trigger)
            setOptions(Object.keys(HeaderUserInfoList).map(item => ({ label: item, value: item })))
            const newObj = list.map(item => ({ ...userInfoButtonList()[item], isEnabled: true }))
            const oldObj = Object.values(userInfoButtonList()).filter(e => list.indexOf(e.uuid) === -1)
            setDataSource([...newObj, ...Object.values(oldObj)])
        }
    }, [data])

    const onDragEnd = ({ active, over }) => {
        if (active.id !== over?.id) {
            setDataSource(prev => {
                const activeIndex = prev.findIndex(i => i.uuid === active.id)
                const overIndex = prev.findIndex(i => i.uuid === over?.id)
                return arrayMove(prev, activeIndex, overIndex)
            })
        }
    }
    const SwitchChange = (uuid, e) => {
        dataSource.find(v => v.uuid === uuid).isEnabled = e
        setDataSource([...dataSource])
    }

    const UserSubmit = () => {
        ModalEvent.emit({
            HeaderUserInfoSet: {
                type: TypeSelect,
                trigger: TriggerSelect,
                list: dataSource.filter(v => v.isEnabled).map(item => item.uuid),
            },
        })
        Off()
    }

    return (
        <div className="HeaderUserInfoSet">
            <div className="label">
                <div>样式类型 : </div>
                <Select value={TypeSelect} bordered={false} options={Options} onChange={setTypeSelect} />
            </div>

            <div className="label">
                <div>触发方式 : </div>
                <Radio.Group
                    options={triggerList}
                    onChange={e => {
                        setTriggerSelect(e.target.value)
                    }}
                    value={TriggerSelect}
                    optionType="button"
                    buttonStyle="solid"
                />
            </div>

            <DndContext onDragEnd={onDragEnd}>
                <SortableContext items={dataSource.map(i => i.uuid)} strategy={verticalListSortingStrategy}>
                    <Table
                        components={{ body: { row: TableRow } }}
                        rowKey="uuid"
                        pagination={false}
                        columns={[
                            { key: 'uuid', width: 50 },
                            { title: '图标', width: 80, dataIndex: 'icon' },
                            { title: '标题', width: 100, dataIndex: 'label' },
                            { title: '简介', dataIndex: 'content' },
                            {
                                title: '开关',
                                width: 80,
                                dataIndex: 'options',
                                render: (_, { uuid, isEnabled }) => [
                                    <Switch key={uuid} checked={isEnabled} onChange={e => SwitchChange(uuid, e)} />,
                                ],
                            },
                        ]}
                        dataSource={dataSource}
                        scroll={{ x: 1000, y: 500 }}
                    />
                </SortableContext>
            </DndContext>
            <div className="Submit">
                <Button type="primary" onClick={UserSubmit}>
                    保存
                </Button>
            </div>
        </div>
    )
}
